<template>
  <view class="course-detail-container">
    <!-- 视频展示区 -->
    <view class="video-container">
      <!-- 视频播放器 -->
      <!--          v-if="productInfo.type===2"-->
      <video
          v-if="productInfo.videoUrl"
          id="myVideo"
          :src="productInfo.videoUrl"
          :initial-time="productInfo.videoProgress || 0"
          :poster="productInfo.image"
          @timeupdate="handleTimeUpdate"
          @ended="handleEnded"
          @play="handlePlay"
          @pause="handlePause"
          controls
          :show-center-play-btn="true"
          :enable-progress-gesture="true"
          @click="handleClick"
          @doubleclick="handleDoubleClick"
          :enable-auto-rotation="true"
          object-fit="cover"
          @fullscreenchange="handleFullscreenChange"
          @controlschange="handleControlsChange"
      >
        <!--        <cover-view style="width: 50rpx;height: 50rpx;background-color: red">11111</cover-view>-->
        <cover-view :class="['speed-float-group2', { visible: areControlsVisible, fullscreen: isFullscreen }]">
          <cover-view
              v-for="(item, idx) in speedBalls"
              :key="idx"
              :class="['speed-float-mini2', `pos-${idx}`, { show: showSpeedBalls }]"
              @click.stop="handleSpeedOptionClick(item)"
          >
            {{ item.label }}
          </cover-view>
          <cover-view class="speed-float-ball2" @click.stop="toggleSpeedBalls">
            <cover-image :src="IMAGE_CONFIG.logoT" :style="{ width: isFullscreen ? '30rpx' : '40rpx', height: isFullscreen ? '30rpx' : '40rpx' }"></cover-image>
            <cover-view>倍速</cover-view>
          </cover-view>
        </cover-view>
      </video>
      <image v-else :src="productInfo.image" mode="aspectFill" style="width: 100%;height: 100%" ></image>
      <view class="try_it" v-if="!productInfo.isBuy && productInfo.videoUrl">试看</view>

      <!-- 双击播放/暂停图标 -->
      <view v-if="showPlayIcon" class="play-icon" :class="{ 'play-icon-show': showPlayIcon }">
        <text>{{ isPlaying ? '❚❚' : '▶' }}</text>
      </view>

      <!-- 试看结束提示 -->
      <view v-if="isTrialEnd" class="trial-overlay" @click="replayTrial">
        <view class="trial-content">
          <text class="trial-title">试看结束</text>
          <text class="trial-desc">您已观看完试看内容，购买后可观看完整版</text>
        </view>
      </view>
    </view>
    <!-- 课程信息区 -->
    <view class="course-info">
      <view class="course-title">{{ productInfo.name }}</view>
      <view class="logo" @click.stop="goStore(productInfo.merId)">
        <image :src="avatar"></image>
      </view>
      <view class="course-rating">
        <view class="star" v-for="(star, index) in productInfo.courseScore" :key="index">★</view>
        <view class="rating-score">{{ productInfo.courseScore }}分</view>
        <view class="study-num">{{ Math.floor(productInfo.sales) + Math.floor(productInfo.ficti) || 0 }}人学习</view>
        <view class="study-num">{{ productInfo.type === 0 ? '线下课' : '线上课' }}</view>
      </view>
      <view class="course_description">
        <view class="content">
          {{ productInfo.intro }}
        </view>

      </view>
      <view class="course-price" v-if="!productInfo.isBuy || productInfo.type===0">
        <view class="original-price">原价: ¥{{ productInfo.otPrice }}</view>
        <view class="current-price">¥{{ productInfo.price }}</view>
      </view>
      <view class="" v-if="productInfo.expireType">
        有效期限：{{ productInfo.expireType==='PERMANENT' ?'永久有效':productInfo.expireType==='FIXED'?`自购买日起有效期为${productInfo.expireValue}天`:formatTime(countdown) }}
      </view>
      <view class="course-interaction">
        <view class="state" @click="like" :class="productInfo.isLike?'yes':'no'">
          <image class="icon" :src="productInfo.isLike?IMAGE_CONFIG.like2:IMAGE_CONFIG.like1"></image>
          <view class="num">{{ productInfo.likeCount }}</view>
        </view>
        <view class="state" @click="step" :class="productInfo.isTrample?'yes':'no'">
          <image class="icon" :src="productInfo.isTrample?IMAGE_CONFIG.trample2:IMAGE_CONFIG.trample1"></image>
          <view class="num">{{ productInfo.trampleCount }}</view>
        </view>
        <view class="state" @click="setCollect" :class="productInfo.isCollection?'yes':'no'">
          <image class="icon" :src="productInfo.isCollection?IMAGE_CONFIG.collection2:IMAGE_CONFIG.collection1"></image>
          <view class="num">{{ productInfo.collectionCount }}</view>
        </view>
        <view>
          <view class="state">
            <image class="icon" @click="listenerActionSheet" :src="IMAGE_CONFIG.state" v-if="isForward"></image>
            <view v-else style="width: 48rpx;height: 48rpx">

              <view :class="['state-anim', { 'state-anim--show': isForward2 }]">
                <image class="icon" :src="IMAGE_CONFIG.state"></image>
              </view>
            </view>
            <view class="num">{{ productInfo.forwardCount }}</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 授课老师信息区 -->
    <view class="teacher-info">
      <view class="teacher-header">
        <view class="teacher-label">授课老师</view>
        <view class="teacher_introduction">
          <view class="teacher-avatar">
            <image :src="teacher.avatar"></image>
          </view>
          <view class="teacher-name" v-if="teacher">
            <view class="name">{{ teacher.name }}</view>
            <view class="concern" @click="concern" :class="productInfo.isFollow?'concernYse':'concernNo'">
              {{ productInfo.isFollow ? '已关注' : '+关注' }}
            </view>
            <view class="private-messages" @click="privateMessages=true">私信</view>
            <view class="title">{{ teacher.title }}</view>
            <view class="teacher-desc" :class="{ 'expanded': isTeacherDescExpanded }" @click="toggleTeacherDesc">
              {{ teacher.intro }}
              <text class="expand-text" v-if="teacher.intro && teacher.intro.length > 50">
                {{ isTeacherDescExpanded ? '收起' : '展开' }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 适用门店区 -->
    <view class="store-available" v-if="productInfo.type === 0">
      <view class="store-title">
        <text class="store-label">适用门店</text>
        <text v-if="productInfo.locationList && productInfo.locationList.length > 1" class="more-btn" @click="showAllStores = !showAllStores">
          {{ showAllStores ? '收起' : '展开全部门店' }}
        </text>
      </view>
      <view class="msg-content" :class="{ 'slide-down': showAllStores }">
        <view v-for="(store, idx) in productInfo.locationList" :key="idx" class="store-card">
          <image class="store-img" :src="store.image" mode="aspectFill" />
          <view class="store-info">
            <view class="store-header">
              <text class="store-title">{{ store.name }}</text>
              <view class="store-actions">
                <image class="icon-btn" :src="IMAGE_CONFIG.diZhi" @click.stop="openMap(store)" />
                <image class="icon-btn" :src="IMAGE_CONFIG.dianHua" @click.stop="callStore(store.contact)" />
              </view>
            </view>
            <view class="store-status-row">
              <text class="store-status" :class="isStoreOpen(store) ? 'open' : 'closed'">
                {{ isStoreOpen(store) ? '营业中' : '休息中' }}
              </text>
              <text class="store-time">{{ store.openTime }}-{{ store.closeTime }}</text>
            </view>
            <view class="store-address-row">
              <text class="store-distance">{{ store.distance || '--' }}</text>
              <text class="store-address">{{ store.address }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 课程大纲区 -->
    <view class="course-outline">
      <view class="outline-header">
        <text class="outline-label">课程大纲</text>
      </view>
      <TreeView
          ref="treeView"
          :rootData="productInfo.courseOutline"
          @toggle="onNodeToggled"
          :isBuy="productInfo.isBuy">
      </TreeView>
    </view>

    <!-- 课程评价部分 -->
    <comment :evaluationCount="evaluationCount" :evaluations="evaluations" :isEvaluation="isEvaluation"
             :masterProductId="id" :orderNo="productInfo.orderNo" :isBuy="productInfo.isBuy"></comment>

    <!-- 课程资料部分 -->
    <information :shownMaterials="courseMaterials" :showAllMaterials="showAllMaterials"
                 :masterProductId="id"></information>

    <view style="height: 40px;width: 100%"></view>
    <!--  底部  -->
    <view class="bottom-buttons-container">
      <view class="report-button">
        <image class="report-icon" :src="IMAGE_CONFIG.juBao"></image>
        <text class="report-text" style="margin-right: 20rpx;" @click="handleReport">
          举报
        </text>
        <image class="report-icon" :src="IMAGE_CONFIG.fanKui"></image>
        <text class="report-text" @click="jumpFeedback">
          反馈
        </text>
      </view>
      <button class="buy-button" @click="goBuy" v-if="!productInfo.isBuy && productInfo.type===5">立即购买</button>
      <button class="buy-button" @click="joinCart" v-if="productInfo.type===0">加入购物车</button>
      <button class="buy-button" @click="goBuy" v-if="productInfo.type===0">立即购买</button>
    </view>

    <!-- 分享按钮 -->
    <u-popup :show="posters" @close="posterImageClose" :round="20">
      <view class="share-popup">
        <view class="share-title">分享课程</view>
        <view class="share-desc">邀请好友一起学习，收获更多成长！</view>
        <view class="share-actions acea-row row-middle">
          <!-- #ifndef MP -->
          <!--          <button class="share-btn item" hover-class="none" v-if="weixinStatus === true" @click="H5ShareBox = true">-->
          <!--            <image src="../../activity/static/images/weixin.png" class="share-icon"></image>-->
          <!--            <text>微信好友</text>-->
          <!--          </button>-->
          <!-- #endif -->
          <!-- #ifdef MP -->
          <button class="share-btn item" open-type="share" hover-class="none">
            <image src="https://fengqinghui.oss-cn-hangzhou.aliyuncs.com/monkey/monkey/weixin.png" class="share-icon"></image>
            <text>微信好友</text>
          </button>
          <!-- #endif -->
          <!-- #ifdef APP-PLUS -->
          <!--          <view class="share-btn item" @click="appShare('WXSceneSession')">-->
          <!--            <view class="iconfont icon-weixin3"></view>-->
          <!--            <text>微信好友</text>-->
          <!--          </view>-->
          <!--          <view class="share-btn item" @click="appShare('WXSenceTimeline')">-->
          <!--            <view class="iconfont icon-pengyouquan"></view>-->
          <!--            <text>微信朋友圈</text>-->
          <!--          </view>-->
          <!-- #endif -->
          <!-- #ifdef MP  -->
          <button class="share-btn item" hover-class="none" @click="savePosterPath">
            <image src="https://fengqinghui.oss-cn-hangzhou.aliyuncs.com/monkey/monkey/haibao.png" class="share-icon"></image>
            <text>保存海报</text>
          </button>
          <!-- #endif -->
        </view>
        <view class="share-tip">点击上方按钮选择分享方式</view>
      </view>
    </u-popup>

    <!--私信-->
    <u-popup :show="privateMessages" @close="close" :round="20">
      <view class="contact-popup">
        <view class="contact-title">联系老师</view>
        <view class="contact-desc">如有疑问可通过以下方式联系老师</view>
        <view class="contact-card" @click="copyToClipboard(teacher.email)">
          <text class="contact-label">邮箱：</text>
          <text class="contact-value">{{ teacher.email }}</text>
          <text class="contact-copy">点击复制</text>
        </view>
        <view class="contact-card" @click="callTeacher">
          <text class="contact-label">电话：</text>
          <text class="contact-value">{{ teacher.phone }}</text>
          <text class="contact-copy">点击拨打</text>
        </view>
        <view class="contact-tip">请在合理时间联系老师，勿打扰休息</view>
      </view>
    </u-popup>
    <uni-popup ref="popupRef" type="center" :maskClick="false">
      <view class="popup-content">
        <view class="font" style="font-size: 1rem">课程下架或删除</view>
        <view class="font" style="margin: 40rpx auto 0;background-color: #8B4513;border-radius: 20px;padding: 10rpx;color: white;
            width: 50%" @click="closePopup">返回</view>
      </view>
    </uni-popup>

    <!--    <view class="poster-pop" v-if="canvasStatus">-->
    <!--      <image :src="imagePath"></image>-->
    <!--    </view>-->
    <view class="canvas" style="position: absolute;top: -2000px;z-index: -1;right: 0">
      <canvas style="width: 750px; height: 1190px" canvas-id="firstCanvas"></canvas>
      <canvas canvas-id="qrcode" :style="{ width: `${qrcodeSize}px`, height: `${qrcodeSize}px` }"/>
    </view>
  </view>
</template>

<script>
import comment from "../../../components/courseDetails/comment.vue";
import information from "../../../components/courseDetails/information.vue";
import {
  collectAdd,
  collectCancel, getProductCode,
  getProductDetail,
  getReplyConfig, getReplyList,
  getReplyProduct,
  postCartAdd
} from "../../../api/product";
import {onGetPreOrder} from "../../../libs/order";
import {
  Debounce
} from "@/utils/validate.js";
import {
  toLogin
} from "@/libs/login.js";
import {
  ProductTypeEnum,
  ProductMarketingTypeEnum,
} from "@/enums/productEnums";
import {getCartCounts} from "../../../api/order";
import {mpQrcode} from "../../../api/api";
import {base64src} from "../../../utils/base64src";
import {imageBase64} from "../../../api/public";
import {HTTP_H5_URL} from "../../../config/app";
import {
  mapGetters
} from "vuex";
import {
  getCourseMaterials,
  getDetail,
  postCancelLikes,
  postCompleted, postFollow,
  postForward,
  postLike,
  postNotTrample, postRecord,
  postTrample, postUnfollow
} from "../../../api/new";
import TreeView from "../../../components/courseDetails/treeView.vue";
import {IMAGE_CONFIG} from '@/utils/imageConfig'

export default {
  components: { TreeView, comment, information},

  data() {
    return {
      IMAGE_CONFIG: IMAGE_CONFIG.index,
      canvasStatus: false, //是否显示海报
      qrcodeSize: 600,
      posterbackgd: "https://fengqinghui.oss-cn-hangzhou.aliyuncs.com/monkey/monkey/posterbackgd.png",
      ProductMarketingTypeEnum: ProductMarketingTypeEnum,
      ProductTypeEnum: ProductTypeEnum,
      imagePath: '', //海报路径
      imgTop: '',
      H5ShareBox: false, //公众号分享图片
      posters: false,
      privateMessages: false,
      weixinStatus: false,
      masterProductId: 0, //活动商品中主商品id
      PromotionCode: "", //二维码图片
      productInfo: {},
      teacher: {},
      // 控制是否显示更多大纲内容
      showAllOutline: false,
      // 当前显示的大纲内容
      shownOutline: [],
      // 控制视频播放状态
      isPlaying: false,
      // 当前播放时间（秒）
      currentTime: 0,
      // 试看是否结束
      isTrialEnd: false,
      // 计时器
      timer: null,
      // 是否显示播放/暂停图标
      showPlayIcon: false,
      // 点击计时器
      clickTimer: null,
      // 上次点击时间
      lastClickTime: 0,
      videoDirection: 'vertical',
      areControlsVisible: false,
      isFullscreen: false,
      // 评价数量
      evaluationCount: 0,
      isEvaluation: true,
      // 评价数据
      evaluations: [],
      // 课程资料数据
      courseMaterials: [],
      // 控制是否显示更多资料
      showAllMaterials: true,
      id: undefined,
      v: 0,
      productValue: [], //系统属性
      attr: {
        cartAttr: false,
        productAttr: [],
        productSelect: {},
      },
      outlineId: undefined,
      attrValueId: undefined,
      marketingType: 0, //视频号普通商品营销类型
      avatar:'',
      merId: '',
      // 新增经纬度字段
      userLat: null,
      userLng: null,
      // 老师介绍展开状态
      isTeacherDescExpanded: false,
      isForward:false,
      isForward2:false,
      countdown: 0, // 单个订单倒计时
      countdownInterval: null, // interval句柄
      showAllStores: false, // 门店展开/收起
      currentPlaybackRate: 1.0,
      showSpeedBalls: false,
      speedBalls: [
        { label: '0.5x', value: 0.5 },
        { label: '1x', value: 1 },
        { label: '1.5x', value: 1.5 },
        { label: '1.75x', value: 1.75 },
        { label: '2x', value: 2 },
      ],
      error:'',
      _savingPoster: false,
    };
  },
  onLoad(options) {
    this.id = options.id
    this.remainingTime()
  },
  mounted() {
    this.getDetail()
  },
  computed: mapGetters(["isLogin", "uid", "chatUrl", "globalData"]),
  watch: {
    'productInfo.expireValue': function() {
      if(this.productInfo.expireType==='DATE'){
        this.startCountdown();
      }
    }
  },
  methods: {
    startCountdown() {
      if (!this.productInfo || !this.productInfo.expireValue) return;
      this.updateCountdown();
      if (this.countdownInterval) clearInterval(this.countdownInterval);
      this.countdownInterval = setInterval(this.updateCountdown, 1000);
    },
    updateCountdown() {
      if (!this.productInfo || !this.productInfo.expireValue) {
        this.countdown = 0;
        return;
      }
      const cancelTime = this.productInfo.expireValue > 1e12 ? Math.floor(this.productInfo.expireValue / 1000) : this.productInfo.expireValue;
      const now = Math.floor(Date.now() / 1000);
      const remain = cancelTime - now;
      this.countdown = remain > 0 ? remain : 0;
    },
    formatTime(seconds) {
      if (seconds <= 0) return '已到期';
      const days = Math.floor(seconds / (24 * 3600));
      const hours = Math.floor((seconds % (24 * 3600)) / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);

      let result = '';
      if (days > 0) result += `${days}天`;
      if (hours > 0 || days > 0) result += `${hours}小时`;
      result += `${minutes}分钟`;
      return `还有${result}`;
    },
    goStore(id) {
      uni.navigateTo({
        url: `/pages/merchant/home/index?merId=${id}`
      })
    },
    close() {
      this.privateMessages = false;
    },
    // 打开弹窗
    openPopup() {
      this.$refs.popupRef.open();
    },

    // 关闭弹窗
    closePopup() {
      uni.navigateBack();
    },
    concern() {
      if (this.productInfo.isFollow) {
        postUnfollow(this.productInfo.id).then(res => {
          uni.showToast({
            title: '取消关注课程成功！',
            icon: 'success',
          });
          this.productInfo.isFollow = !this.productInfo.isFollow
        })
      } else {
        postFollow(this.productInfo.id, 0).then(res => {
          uni.showToast({
            title: '关注课程成功！',
            icon: 'success',
          });
          this.productInfo.isFollow = !this.productInfo.isFollow
        })
      }
    },
    like() {
      if (this.productInfo.isLike) {
        postCancelLikes(this.id).then(res => {
          if(res.code === 200){
            uni.showToast({
              title: '取消点赞成功！',
              icon: 'success',
            });
            this.$set(this.productInfo, "isLike", !this.productInfo.isLike);
            this.productInfo.likeCount--
          }
        })
      } else {
        postLike(this.id, 0).then(res => {
          if(res.code === 200){
            uni.showToast({
              title: '点赞成功！',
              icon: 'success',
            });
            this.$set(this.productInfo, "isLike", !this.productInfo.isLike);
            this.productInfo.likeCount++
          }
        })
      }
    },
    step() {
      if (this.productInfo.isTrample) {
        postNotTrample(this.id).then(res => {
          if(res.code === 200){
            uni.showToast({
              title: '取消踩成功！',
              icon: 'success',
            });
            this.$set(this.productInfo, "isTrample", !this.productInfo.isTrample);
            this.productInfo.trampleCount--
          }
        })
      } else {
        postTrample(this.id, 0).then(res => {
          if(res.code === 200){
            uni.showToast({
              title: '踩成功！',
              icon: 'success',
            });
            this.$set(this.productInfo, "isTrample", !this.productInfo.isTrample);
            this.productInfo.trampleCount++
          }
        })
      }
    },
    /**
     *
     *
     * 收藏商品
     */
    setCollect: Debounce(function () {
      let that = this;
      if (this.isLogin === false) {
        toLogin("isLogin");
      } else {
        let id =
            Number(this.masterProductId) > 0 ?
                this.masterProductId :
                this.productInfo.id;
        if (this.productInfo.isCollection) {
          collectCancel({
            ids: id,
          }).then((res) => {
            if(res.code === 200){
              that.$set(that.productInfo, "isCollection", !that.productInfo.isCollection);
              uni.showToast({
                title: '取消收藏！',
                icon: 'success',
              });
              this.productInfo.collectionCount--
            }
          });
        } else {
          collectAdd(id).then((res) => {
            if(res.code === 200){
              that.$set(that.productInfo, "isCollection", !that.productInfo.isCollection);
              uni.showToast({
                title: '收藏成功！',
                icon: 'success',
              });
              this.productInfo.collectionCount++
            }
          });
        }
      }
    }),
    jumpFeedback() {
      uni.navigateTo({
        url: '/pages/complaint/index'
      })
    },
    // 格式化剩余时间为 分:秒 格式
    remainingTime() {
      const seconds = Math.max(0, this.trialDuration - this.currentTime);
      const minutes = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${minutes}:${secs.toString().padStart(2, '0')}`;
    },

    // 节点展开/折叠回调
    onNodeToggled(node) {
      if (this.productInfo.isBuy) {
        clearInterval(this.timer2);
        this.$set(this.productInfo, 'videoUrl', node.videoUrl)
        this.$set(this.productInfo, 'videoProgress', (node.isFinished?0:node.videoProgress))
        this.$set(this.productInfo, 'image', node.cover)
        this.outlineId = node.id
        this.$forceUpdate()
        this.$nextTick(() => {
          const videoContext = uni.createVideoContext('myVideo', this);
          videoContext.play();
        })
      } else {
        uni.showToast({
          icon: 'none',
          title: '请先购买课程'
        });
      }
    },
    ShareInfo() {
      let data = this.productInfo;
      let href = location.href;
      if (this.$wechat.isWeixin() && this.publicLoginType == 1) {
        if (this.marketingType === ProductMarketingTypeEnum.Groupbuying) {
          href =
              href.split("?")[0] +
              "?id=" +
              this.id +
              "&sd=" +
              this.uid +
              "&mt=" +
              this.marketingType +
              "&gd=" +
              this.groupActivityId;
        } else {
          href = href.split("?")[0] +
              "?id=" +
              this.id +
              "&sd=" +
              this.uid +
              "&mt=" +
              this.marketingType
        }
        let configAppMessage = {
          desc: data.intro ? data.intro : '',
          title: data.name,
          link: href,
          imgUrl: data.image,
        };
        this.$wechat
            .wechatEvevt(
                [
                  "updateAppMessageShareData",
                  "updateTimelineShareData",
                  "onMenuShareAppMessage",
                  "onMenuShareTimeline",
                ],
                configAppMessage
            )
            .then((res) => {
            })
            .catch((err) => {
              console.log(err);
            });
      }
    },
    async getDetail() {
      uni.showLoading({
        title: '加载中...'
      });
      this.isForward = false;
      this.isForward2 = false;
      let that = this
      await getProductDetail(this.id, 0, 0, '').then(async res => {
        this.isForward2=true;
        let productInfo = res.data.productInfo;
        that.$set(that, "productInfo", productInfo);
        that.$set(that.productInfo, "videoUrl", productInfo.videoLink);
        that.$set(that, "teacher", productInfo.teacher);
        that.$set(that, "masterProductId", res.data.masterProductId || 0);
        this.avatar = res.data.merchantInfo.avatar
        if(this.productInfo.expireType==='DATE'){
          this.startCountdown();
        }
        that.attrValueId = res.data.productValue['默认'].id
        that.$refs.treeView.treeData = that.$refs.treeView.addTreePropertiesReactive(this.productInfo.courseOutline, this)
        let id =
            Number(that.masterProductId) > 0 ? that.masterProductId : that.id;
        await that.getReply(id)
        // 页面进入时获取用户经纬度
        uni.getLocation({
          type: 'gcj02',
          success: (res) => {
            this.userLat = res.latitude;
            this.userLng = res.longitude;
            this.calcAllStoreDistance();
          },
          fail: () => {
            // 定位失败也要刷新门店距离为--
            this.calcAllStoreDistance();
          }
        });
        uni.hideLoading();
        if (that.isLogin) {
          //#ifdef H5
          that.make(that.uid);
          that.ShareInfo();
          await this.getImageBase64(this.productInfo.image);
          // #endif
        }
        // #ifdef MP
        await that.getQrcode();
        // #endif
        // #ifdef MP
        that.imgTop = res.data.productInfo.image;
        // #endif
        // #ifndef H5
        await that.downloadFilestoreImage();
        // setTimeout(() => {
        //   this.isForward = true;
        // }, 5000);
        // #endif
      }).catch(error => {
        uni.hideLoading();
        this.openPopup()
      })
      let propagation = {
        id: this.id,
        limit: 10,
        page: 1,
      }
      getCourseMaterials(propagation).then(res => {
        this.courseMaterials = res.data
      })
      if (that.loadend) return;
      getReplyList(that.id, {
        page: 1,
        limit: 2,
        type: 0,
      }).then(res => {
        this.evaluations = res.data.list
        this.evaluationCount = res.data.total
      })
    },
    getReply(id) {
      getReplyConfig(id).then((res) => {
        this.$set(this, "evaluationCount", res.data.replyChance);
      });
      getReplyProduct(id).then((res) => {
        this.evaluations = res.data.productReply ? [res.data.productReply] : [];
      });
    },
    showMoreOutline() {
      this.showAllOutline = true;
      this.shownOutline = this.courseOutline;
    },
    // 监听视频播放时间
    handleTimeUpdate(e) {
      this.currentTime = e.detail.currentTime;
      if(this.outlineId){
        postRecord({courseId: this.id, outlineId: this.outlineId, videoProgress: Math.floor(this.currentTime)}).then()
      }
    },
    // 暂停视频播放
    pauseVideo() {
      const videoContext = uni.createVideoContext('myVideo', this);
      videoContext.pause();
      this.isPlaying = false;
    },
    // 播放视频
    playVideo() {
      const videoContext = uni.createVideoContext('myVideo', this);
      videoContext.play();
      this.isPlaying = true;
    },
    // 视频播放事件
    handlePlay() {
      this.isPlaying = true;
      const videoContext = uni.createVideoContext('myVideo', this);
      videoContext.playbackRate(this.currentPlaybackRate);
    },
    // 视频暂停事件
    handlePause() {
      this.isPlaying = false;
      // 清除计时器
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    // 视频播放结束
    handleEnded() {
      // 试看视频播放结束，可能需要提示用户
      if (!this.productInfo.isBuy) {
        this.isTrialEnd = true;
      } else {
        clearInterval(this.timer2);
        postCompleted(this.id, this.outlineId).then(res=>{
          getProductDetail(this.id, 0, 0, '').then(res => {
            this.$refs.treeView.treeData = this.$refs.treeView.addTreePropertiesReactive(this.productInfo.courseOutline, this)
          })
        })
      }
      this.isPlaying = false;
    },
    // 处理单击事件（用于检测双击）
    handleClick(e) {
      const now = Date.now();
      // 判断是否是双击
      if (now - this.lastClickTime < 300) {
        // 双击事件
        clearTimeout(this.clickTimer);
        this.handleDoubleClick(e);
      } else {
        // 单击事件
        this.lastClickTime = now;
        this.clickTimer = setTimeout(() => {
          // 这里可以添加单击事件处理逻辑
          this.areControlsVisible = !this.areControlsVisible;
        }, 300);
      }
    },
    // 处理双击事件
    handleDoubleClick(e) {
      e.stopPropagation();
      if (this.isPlaying) {
        this.pauseVideo();
      } else {
        this.playVideo();
      }
      // 显示播放/暂停图标2秒
      this.showPlayIcon = true;
      setTimeout(() => {
        this.showPlayIcon = false;
      }, 800);
    },
    handleReport() {
      uni.navigateTo({
        url: '/pages/complaint/report?id=' + this.productInfo.id
      })
    },
    /*
			 * 加入购物车
			 */
    goCat: function (num) {
      let that = this,
          productSelect = that.productValue[this.attrValue];
      //打开属性
      if (that.attrValue) {
        //默认选中了属性，但是没有打开过属性弹窗还是自动打开让用户查看默认选中的属性
        that.attr.cartAttr = !that.isOpen ? true : false;
      } else {
        if (that.isOpen) that.attr.cartAttr = true;
        else that.attr.cartAttr = !that.attr.cartAttr;
      }
      //只有关闭属性弹窗时进行加入购物车
      if (that.attr.cartAttr === true && that.isOpen === false)
        return (that.isOpen = true);
      //如果有属性,没有选择,提示用户选择
      if (
          that.attr.productAttr.length &&
          productSelect.stock === 0 &&
          that.isOpen === true
      )
        return that.$util.Tips({
          title: "产品库存不足，请选择其它",
        });
      if (num === 1) {
        let q = {
          productId: parseFloat(that.id),
          cartNum: parseFloat('1'),
          isNew: false,
          productAttrUnique: this.attrValueId
        };
        postCartAdd(q)
            .then(function (res) {
              that.isOpen = false;
              that.attr.cartAttr = false;
              that.$util.Tips({
                title: "添加购物车成功",
                success: () => {
                  that.getCartCount(true);
                },
              });
            })
            .catch((res) => {
              that.isOpen = false;
              return that.$util.Tips({
                title: res,
              });
            });
      } else {
        this.getPreOrder();
      }
    },
    /**
     * 获取购物车数量
     * @param boolean 是否展示购物车动画和重置属性
     */
    getCartCount: function (isAnima) {
      let that = this;
      getCartCounts(true, "total")
          .then((res) => {
            that.CartCount = res.data.count;
            //加入购物车后重置属性
            if (isAnima) {
              that.animated = true;
              setTimeout(function () {
                that.animated = false;
              }, 500);
            }
          })
          .catch((err) => {
            that.CartCount = 0;
          });
    },
    /**
     * 打开属性加入购物车
     *
     */
    joinCart: Debounce(function (e) {
      //是否登录
      if (this.isLogin === false) {
        toLogin();
      } else {
        this.goCat(1);
      }
    }),
    /**
     * 立即购买
     */
    goBuy: Debounce(function (e) {
      if (this.isLogin === false) {
        toLogin();
      } else {
        this.goCat(0);
      }
    }),
    /**
     * 预下单
     */
    getPreOrder: function () {
      if (
          this.marketingType === ProductMarketingTypeEnum.Groupbuying &&
          this.attr.productSelect.cart_num > this.buyLimitNum
      ) {
        this.isOpen = false;
        return this.$util.Tips({
          title: "超出限购数量",
        });
      }
      if (this.attr.productSelect.cart_num < 1) {
        uni.showToast({
          title: "单次可购买商品数量范围为 1~99",
          icon: "none",
        });
      } else {
        let types = "";
        // switch (this.marketingType) {
        switch (0) {
          case ProductMarketingTypeEnum.Normal:
            if (this.productInfo.type === 4) {
              types = "video";
            } else {
              types = "buyNow";
            }
            break;
          case ProductMarketingTypeEnum.Seckill:
            types = "seckill";
            break;
          case ProductMarketingTypeEnum.Groupbuying:
            types = "group";
            break;
        }
        onGetPreOrder(types, [{
          // attrValueId: parseFloat(this.productInfo.id),
          attrValueId: parseFloat(this.attrValueId),
          productId: parseFloat(this.id),
          productNum: parseFloat('1'),
          groupBuyActivityId: parseFloat(this.groupActivityId),
          groupBuyRecordId: 0,
        },]);
      }
      this.isOpen = false;
    },
    /**
     * 分享打开
     *
     */
    listenerActionSheet: function () {
      this.goPoster();
      this.posters = true;
      // #ifdef H5
      if (!this.isLogin) {
        toLogin();
      } else {
        if (this.$wechat.isWeixin()) {
          this.weixinStatus = true;
        }
      }
      // #endif
    },
    closePosters: function () {
      this.posters = false;
      this.currentPage = false;
    },
    //隐藏海报
    posterImageClose: function () {
      this.canvasStatus = false;
      this.posters = false;
    },
    //替换安全域名
    setDomain: function (url) {
      url = url ? url.toString() : "";
      //本地调试打开,生产请注销
      if (url.indexOf("https://") > -1) return url;
      else return url.replace("http://", "https://");
    },
    //获取海报产品图（解决跨域问题，只适用于小程序）
    downloadFilestoreImage: function () {
      let that = this;
      uni.downloadFile({
        url: that.setDomain(that.productInfo.image),
        success: function (res) {
          that.storeImage = res.tempFilePath;
          that.isForward = true;
        },
        fail: function () {
          that.isForward = true;
          return that.$util.Tips({
            title: "",
          });
          that.storeImage = "";
        },
      });
    },
    // 小程序关闭分享弹窗；
    goFriend: function () {
      this.posters = false;
    },
    // 小程序二维码
    getQrcode() {
      let that = this;
      let data;
      if (this.marketingType === ProductMarketingTypeEnum.Groupbuying) {
        data = {
          scene: "id=" +
              this.id +
              "&sd=" +
              that.uid +
              "&mt=" +
              2 +
              "&gd=" +
              this.groupActivityId,
          page: "pages/discover/courseDetails/index",
        };
      } else {
        data = {
          scene: "id=" + this.id + "&sd=" + that.uid + "&mt=" + that.marketingType,
          page: "pages/discover/courseDetails/index",
        };
      }
      mpQrcode(data)
          .then((res) => {
            base64src(res.data.code, Date.now(), (res) => {
              that.PromotionCode = res;
            });
          })
          .catch((err) => {
            that.errT = err;
          });
    },
    // 生成二维码；
    make(uid) {
      let href;
      if (this.marketingType === ProductMarketingTypeEnum.Groupbuying) {
        href =
            location.href.split("?")[0] +
            "?id=" +
            this.id +
            "&sd=" +
            this.uid +
            "&mt=" +
            this.marketingType +
            "&gd=" +
            this.groupActivityId;
      } else {
        href =
            location.href.split("?")[0] +
            "?id=" +
            this.id +
            "&sd=" +
            this.uid +
            "&mt=" +
            this.marketingType;
      }
      uQRCode.make({
        canvasId: "qrcode",
        text: href,
        size: this.qrcodeSize,
        margin: 10,
        success: (res) => {
          this.PromotionCode = res;
        },
        complete: () => {
        },
        fail: (res) => {
          this.$util.Tips({
            title: "海报二维码生成失败！",
          });
        },
      });
    },
    getImageBase64: function (images) {
      let that = this;
      imageBase64({
        url: images,
      }).then((res) => {
        that.imgTop = res.data.code;
      });
    },

    /**
     * 生成海报
     */
    goPoster: async function () {
      let that = this;
      postForward(this.id, 'course');
      uni.showLoading({
        title: "海报生成中",
        mask: true,
      });

      try {
        that.posters = false;

        if (!that.PromotionCode) {
          uni.hideLoading();
          that.$util.Tips({ title: that.errT || '二维码获取失败' });
          return;
        }

        // 等待主图加载
        await new Promise((resolve, reject) => {
          setTimeout(() => {
            if (!that.imgTop) {
              reject(new Error("无法生成商品海报，主图未加载"));
            } else if (!/^https?:\/\//.test(that.imgTop)) {
              reject(new Error("主图地址无效，无法生成海报"));
            } else {
              resolve();
            }
          }, 1000);
        });

        // 下载主图
        const downloadRes = await new Promise((resolve, reject) => {
          uni.downloadFile({
            url: that.imgTop,
            success: (res) => {
              if (res.statusCode === 200) {
                resolve(res.tempFilePath);
              } else {
                const errorMsg = `主图下载失败, 状态码: ${res.statusCode}`;
                console.error(errorMsg, res);
                reject(new Error(errorMsg));
              }
            },
            fail: (err) => {
              const errorMsg = `主图下载失败: URL[${that.imgTop}] ERR[${(err && err.errMsg ? err.errMsg : '未知错误')}]`;
              console.error(errorMsg, err);
              reject(new Error("主图下载失败，请检查网络或域名配置"));
            }
          });
        });

        let arrImages = [
          that.posterbackgd,
          downloadRes,
          that.PromotionCode,
        ];
        let name = that.productInfo.name;
        let price, otPrice;
        if (that.marketingType === that.ProductMarketingTypeEnum.Groupbuying) {
          price = that.groupBuyActivityResponse.activePrice;
          otPrice = that.productInfo.price;
        } else {
          price = that.productInfo.price;
          otPrice = that.productInfo.type === that.ProductTypeEnum.Integral ? that.productInfo.cost : that.productInfo.otPrice;
        }

        // 生成海报
        await new Promise((resolve, reject) => {
          setTimeout(() => {
            try {
              that.$util.PosterCanvas(
                arrImages,
                name,
                price,
                otPrice,
                function (tempFilePath) {
                  that.imagePath = tempFilePath;
                  that.canvasStatus = true;
                  uni.hideLoading();
                  // that.$util.Tips({ title: "海报生成成功", icon: "success" });
                  resolve();
                }
              );
            } catch (e) {
              reject(new Error("生成海报时发生错误"));
            }
          }, 500);
        });

      } catch (e) {
        uni.hideLoading();
        console.error("goPoster error:", e);
        that.$util.Tips({ title: e.message || "生成海报失败" });
      }
    },
    /*
			 * 保存到手机相册
			 */
    savePosterPath: function () {
      let that = this;
      if (that._savingPoster) return; // 防止重复点击
      that._savingPoster = true;
      uni.showLoading({ title: "正在保存...", mask: true });

      function reset() {
        that._savingPoster = false;
        uni.hideLoading();
      }

      function doSave(filePath) {
        console.log("doSave filePath:", filePath);
        uni.saveImageToPhotosAlbum({
          filePath: filePath,
          success: function (res) {
            reset();
            that.posterImageClose && that.posterImageClose();
            that.$util && that.$util.Tips && that.$util.Tips({
              title: "保存成功",
              icon: "success",
            });
          },
          fail: function (res) {
            reset();
            that.$util && that.$util.Tips && that.$util.Tips({
              title: "保存失败",
            });
          },
          complete: function () {
            reset();
          }
        });
      }

      function handleSave() {
        console.log("handleSave, imagePath:", that.imagePath);
        if (/^https?:\/\//.test(that.imagePath)) {
          uni.downloadFile({
            url: that.imagePath,
            success: function (res) {
              console.log("downloadFile success:", res);
              if (res.statusCode === 200) {
                doSave(res.tempFilePath);
              } else {
                reset();
                that.$util && that.$util.Tips && that.$util.Tips({ title: "图片下载失败" });
              }
            },
            fail: function (err) {
              reset();
              console.log("downloadFile fail:", err);
              that.$util && that.$util.Tips && that.$util.Tips({ title: "图片下载失败" });
            }
          });
        } else {
          doSave(that.imagePath);
        }
      }

      uni.getSetting({
        success(res) {
          console.log("getSetting:", res);
          if (!res.authSetting["scope.writePhotosAlbum"]) {
            uni.authorize({
              scope: "scope.writePhotosAlbum",
              success() {
                setTimeout(() => {
                  handleSave();
                }, 300);
              },
              fail() {
                reset();
                that.$util && that.$util.Tips && that.$util.Tips({ title: "授权失败，无法保存图片" });
              }
            });
          } else {
            handleSave();
          }
        },
        fail(err) {
          reset();
          console.log("getSetting fail:", err);
          that.$util && that.$util.Tips && that.$util.Tips({ title: "获取权限失败" });
        }
      });
    },
    // #ifdef APP-PLUS
    appShare(scene) {
      let that = this;
      let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
      let curRoute = routes[routes.length - 1].$page.fullPath; // 获取当前页面路由，也就是最后一个打开的页面路由
      uni.share({
        provider: "weixin",
        scene: scene,
        type: 0,
        href: `${HTTP_H5_URL}${curRoute}&sd=${that.uid}&mt=${this.marketingType}&gd=${this.groupActivityId}`,
        title: that.productInfo.name,
        summary: that.productInfo.intro ? that.productInfo.intro : '',
        imageUrl: that.productInfo.image,
        success: function (res) {
          that.posters = false;
        },
        fail: function (err) {
          uni.showToast({
            title: "分享失败",
            icon: "none",
            duration: 2000,
          });
          that.posters = false;
        },
      });
    },
    // #endif
    // 判断门店是否营业
    isStoreOpen(store) {
      if (!store.openTime || !store.closeTime) return false;
      const now = new Date();
      const pad = n => n < 10 ? '0' + n : n;
      const nowStr = pad(now.getHours()) + ':' + pad(now.getMinutes());
      // 营业时间可能跨天
      if (store.openTime < store.closeTime) {
        // 正常营业时间
        return nowStr >= store.openTime && nowStr < store.closeTime;
      } else {
        // 跨天营业（如22:00-06:00）
        return nowStr >= store.openTime || nowStr < store.closeTime;
      }
    },
    // 跳转到微信地图
    openMap(store) {
      if (!store.latitude || !store.longitude) {
        this.$util && this.$util.Tips ? this.$util.Tips({ title: '门店未配置坐标' }) : uni.showToast({ title: '门店未配置坐标', icon: 'none' });
        return;
      }
      uni.openLocation({
        latitude: Number(store.latitude),
        longitude: Number(store.longitude),
        name: store.name,
        address: store.address
      });
    },
    copyToClipboard(val) {
      if (!val) return;
      uni.setClipboardData({
        data: val + '',
        success: () => {
          uni.showToast({ title: '已复制', icon: 'success', duration: 1500 });
        }
      });
    },
    callStore(phone) {
      if (!phone) return;
      uni.makePhoneCall({ phoneNumber: phone + '' });
    },
    getDistance(lat1, lng1, lat2, lng2) {
      const toRad = d => d * Math.PI / 180;
      const R = 6378137;
      const radLat1 = toRad(lat1);
      const radLat2 = toRad(lat2);
      const a = radLat1 - radLat2;
      const b = toRad(lng1) - toRad(lng2);
      const s = 2 * Math.asin(Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
      ));
      return R * s;
    },
    calcAllStoreDistance() {
      if (
        !this.productInfo ||
        !Array.isArray(this.productInfo.locationList) ||
        this.productInfo.locationList.length === 0
      ) {
        return;
      }
      this.productInfo.locationList.forEach(store => {
        // 兼容后端字段 latitude/longitude
        const lat = Number(store.latitude);
        const lng = Number(store.longitude);
        if (lat && lng && this.userLat && this.userLng) {
          const dist = this.getDistance(this.userLat, this.userLng, lat, lng);
          store.distance = dist > 1000 ? (dist / 1000).toFixed(1) + 'km' : Math.round(dist) + 'm';
        } else {
          store.distance = '--';
        }
      });
      // 按距离从近到远排序
      this.productInfo.locationList.sort((a, b) => {
        // 提取距离的数值（统一为米）
        function parseDistance(d) {
          if (!d || d === '--') return Number.MAX_SAFE_INTEGER;
          if (typeof d === 'number') return d;
          if (d.endsWith('km')) return parseFloat(d) * 1000;
          if (d.endsWith('m')) return parseFloat(d);
          return Number.MAX_SAFE_INTEGER;
        }
        return parseDistance(a.distance) - parseDistance(b.distance);
      });
      this.$forceUpdate && this.$forceUpdate();
    },
    // 切换老师介绍展开/收起状态
    toggleTeacherDesc() {
      this.isTeacherDescExpanded = !this.isTeacherDescExpanded;
    },
    // 给老师拨打电话
    callTeacher() {
      if (!this.teacher.phone) {
        uni.showToast({
          title: '老师电话未配置',
          icon: 'none'
        });
        return;
      }
      uni.makePhoneCall({
        phoneNumber: this.teacher.phone,
        success: () => {
          console.log('拨打电话成功');
        },
        fail: (err) => {
          console.log('拨打电话失败', err);
          uni.showToast({
            title: '拨打电话失败',
            icon: 'none'
          });
        }
      });
    },
    replayTrial() {
      this.isTrialEnd = false;
      // 重新播放试看视频，从头开始
      const videoContext = uni.createVideoContext('myVideo', this);
      videoContext.seek(0);
      videoContext.play();
      this.isPlaying = true;
    },
  },
  onShareAppMessage() {
    return {
      title: this.productInfo.name,
      imageUrl: this.productInfo.image || '',
      path: `/pages/discover/courseDetails/index?id=${this.id}`
    }
  },
  // 组件销毁时清除计时器
  onUnload() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
    if (this.clickTimer) {
      clearTimeout(this.clickTimer);
      this.clickTimer = null;
    }
    if (this.productInfo.isBuy) {
      console.log(this.id)
    }
  },
};
</script>

<style lang="scss" scoped>
// 定义颜色变量
$primary-color: #8F4C38;
$secondary-color: red;
$text-color: #333;
$text-light-color: #666;
$text-lighter-color: #999;
$border-color: #E5E5E5;
$bg-color: #f7f7f7;
$overlay-bg: rgba(0, 0, 0, 0.5);
$icon-color: #999;
$report-text-color: #4B5563;
$buy-button-bg-color: #8B4513;
$buy-button-text-color: #FCFAF6;

// 定义尺寸变量
$base-font-size: 16px;
$header-font-size: 20px;
$subheader-font-size: 18px;
$small-font-size: 14px;
$tiny-font-size: 12px;
$spacing: 10px;
$radius: 5px;
$border-radius: 10px;
$transition-time: 0.3s;
$avatar-size: 40px;
$icon-size: 20px;

// 定义混合器
@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

@mixin padding-size {
  padding: 15px;
  /*border-bottom: 1px solid $text-lighter-color;*/
}

@mixin center-position {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.popup-content{
  width: 400rpx;
  .font{
    text-align: center;

  }
}

.course-detail-container {
  background-color: $bg-color;
  overflow-y: hidden;
}

.video-container {
  position: relative;
  width: 100%;
  height: 300px;

  video {
    width: 100%;
    height: 100%;
  }

  .try_it {
    position: absolute;
    right: $spacing;
    top: $spacing+2;
    background-color: $primary-color;
    padding: 4px 8px;
    border-radius: $border-radius/2;
    color: $buy-button-text-color;
    z-index: 2147483647;
  }

  // 双击播放/暂停图标
  .play-icon {
    @include center-position;
    @include flex-center;
    width: 80px;
    height: 80px;
    background-color: $overlay-bg;
    border-radius: 50%;
    color: white;
    font-size: 36px;
    opacity: 0;
    transition: opacity $transition-time;
    z-index: 10;

    &-show {
      opacity: 1;
    }
  }

  // 试看结束提示
  .trial-overlay {
    @include flex-center;

    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: $bg-color;
    z-index: 20;

    .trial-content {
      background-color: white;
      padding: 20px;
      border-radius: $border-radius;
      text-align: center;
      width: 80%;

      .trial-title {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 10px;
      }

      .trial-desc {
        font-size: 14px;
        color: $text-light-color;
        margin-bottom: 20px;
      }

      .buy-btn {
        background-color: $primary-color;
        color: white;
        border-radius: 5px;
        padding: 10px;
        margin-bottom: 10px;
      }

      .close-btn {
        background-color: #616161;
        color: $text-color;
        border-radius: 5px;
        padding: 10px;
      }
    }
  }

  // 试看倒计时提示
  .countdown {
    position: absolute;
    bottom: 20px;
    right: 20px;
    background-color: $overlay-bg;
    color: white;
    padding: 5px 10px;
    border-radius: 5px;
    font-size: 12px;
    z-index: 5;
  }
}

// 课程信息区
.course-info {
  @include padding-size;
  position: relative;

  .logo {
    position: absolute;
    top: 48rpx;
    right: 15px;
    width: 54px;
    height: 54px;
    image{
      width: 100%; /* 图片宽度撑满容器 */
      height: 100%; /* 图片高度撑满容器 */
      object-fit: cover; /* 图片等比缩放，填满容器，可能裁剪 */
      border-radius: 50%;
    }
  }

  .course-title {
    font-size: $header-font-size;
    font-weight: bold;
    color: $text-color;
    width: 70%;
  }

  .course-rating {
    @include flex-center;
    justify-content: flex-start;
    margin-top: $spacing / 2;

    .star {
      color: gold;
      margin-right: 2px;
    }

    .rating-score {
      margin-left: 5px;
      color: $text-light-color;
    }

    .study-num {
      margin-left: 10px;
      color: $text-light-color;
    }
  }

  .course_description {
    width: 60%;

    .content {

    }
  }

  .course-price {
    @include flex-center;
    justify-content: flex-start;
    margin-top: $spacing / 2;

    .original-price {
      text-decoration: line-through;
      color: $text-lighter-color;
      margin-right: 10px;
    }

    .current-price {
      color: $secondary-color;
      font-size: $header-font-size;
    }
  }

  .course-interaction {
    @include flex-center;
    justify-content: space-evenly;
    margin-top: 30rpx;

    .state {
      text-align: center;

      .icon {
        width: 48rpx;
        height: 48rpx;
      }

      .num {
        text-align: center;
        width: 100%;
        color: #53433F;
      }
    }

    .yes {
      color: #8B4513;
    }

    .no {
      color: #000;
    }
  }
}

// 适用门店区
.store-available {
  @include padding-size;
  border-radius: 10px;
  margin: 20rpx 0;
  .store-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    .store-icon {
      width: 24px;
      height: 24px;
      margin-right: 8px;
    }
    .store-label {
      font-size: $subheader-font-size;
      /*font-weight: bold;*/
      margin-right: $spacing;
      margin-bottom: $spacing;
    }
    .more-btn {
      color: #8B4513;
      cursor: pointer;
      font-size: 15px;
      margin-left: 0;
      margin-bottom: 0;
    }
  }

  .msg-content {
    max-height: 224rpx;
    opacity: 0.85;
    overflow: hidden;
    padding-top: 8px;
    padding-bottom: 0;
    transition: all 0.4s cubic-bezier(.55,0,.1,1);
    &.slide-down {
      max-height: 1000px;
      opacity: 1;
    }
    .store-card {
      display: flex;
      align-items: flex-start;
      border-radius: 16px;
      box-shadow: 0 2px 8px #f3f1ed;
      padding: 20rpx 24rpx;
      margin: 20rpx 0;
      .store-img {
        width: 120rpx;
        height: 120rpx;
        border-radius: 12rpx;
        object-fit: cover;
        flex-shrink: 0;
        margin-right: 20rpx;
      }
      .store-info {
        flex: 1;
        min-width: 0;
        .store-header {
          display: flex;
          align-items: flex-start;
          justify-content: space-between;
          .store-title {
            font-weight: bold;
            color: #222;
            flex: 1;
            min-width: 0;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .store-actions {
            display: flex;
            align-items: center;
            margin-left: 12rpx;
            .icon-btn {
              width: 30rpx;
              height: 30rpx;
              margin-left: 20rpx;
            }
          }
        }
        .store-status-row {
          margin-top: 8rpx;
          display: flex;
          align-items: center;
          .store-status {
            color: #888;
            font-size: 26rpx;
            margin-right: 16rpx;
            &.open { color: #8a4513; font-weight: bold; }
            &.closed { color: #bbb; }
          }
          .store-time {
            color: #888;
            font-size: 26rpx;
          }
        }
        .store-address-row {
          margin-top: 8rpx;
          display: flex;
          align-items: center;
          .store-distance {
            color: #e94f6a;
            font-size: 28rpx;
            margin-right: 12rpx;
            font-weight: 500;
          }
          .store-address {
            color: #888;
            font-size: 28rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            flex: 1;
          }
        }
      }
    }
  }

}

// 授课老师信息区
.teacher-info {
  @include padding-size;

  .teacher-header {
    margin-bottom: $spacing / 2;

    .teacher-label {
      font-size: $subheader-font-size;
      /*font-weight: bold;*/
      margin-right: $spacing;
      margin-bottom: $spacing;
    }

    .teacher_introduction {
      @include flex-center;
      align-items: flex-start;
      justify-content: flex-start;

      .teacher-avatar {
        //width: 50px;
        //height: 50px;
        //overflow: hidden;

        image {
          width: 50px;
          height: 50px;
          border-radius: 50%;
        }
      }

      .teacher-name {
        margin-left: $spacing;
        position: relative;
        width: 100%;

        .name {
          font-size: $base-font-size;
          /*font-weight: bold;*/
        }

        .private-messages {
          font-size: 21rpx;
          position: absolute;
          width: 46px;
          padding: 2px 0;
          text-align: center;
          background-color: #8B4513;
          border: 2px solid #B16F27;
          border-radius: 15px;
          color: #fff;
          top: 0;
          right: 0;
        }

        .title {
          font-size: $small-font-size;
          color: $text-light-color;
        }

        .concern {
          font-size: 21rpx;
          position: absolute;
          top: 0;
          right: 54px;
          padding: 2px 0;
          width: 68px;
          text-align: center;
          border-radius: 15px;
          color: #fff;
        }

        .concernNo {
          background-color: #CC8437;
          border: 2px solid #AE632C;
        }

        .concernYse {
          background-color: #AE632C;
          border: 2px solid #CC8437;
        }
      }

      .teacher-desc {
        font-size: $small-font-size;
        line-height: 1.5;
        color: $text-light-color;
        cursor: pointer;
        position: relative;
        transition: max-height 0.3s cubic-bezier(0.4,0,0.2,1);
        overflow: hidden;
        max-height: 4.5em;
        &.expanded {
          max-height: 500px; // 这里设置一个足够大的最大高度，保证动画效果
        }
        &:not(.expanded) {
          max-height: 4.5em;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }
        .expand-text {
          color: #8B4513;
          font-weight: bold;
          margin-left: 4px;
          display: inline;
        }
      }
    }
  }
}

// 课程大纲区
.course-outline {
  @include padding-size;

  .outline-header {
    @include flex-center;
    justify-content: space-between;
    margin-bottom: $spacing / 2;

    .outline-label {
      font-size: $subheader-font-size;
      /*font-weight: bold;*/
    }

    .more-btn {
      color: $text-light-color;
      cursor: pointer;
    }
  }

  .outline-item {
    @include flex-center;
    justify-content: flex-start;
    margin-bottom: $spacing / 2;
    padding: $spacing / 2;
    //background-color: white;
    border-radius: $radius;

    .item-num {
      width: 20px;
      text-align: center;
      margin-right: $spacing;
      color: $text-lighter-color;
    }

    .item-title {
      flex: 1;
    }

    .item-duration {
      color: $text-lighter-color;
      margin-left: $spacing;
    }

    .item-trial {
      color: $secondary-color;
      margin-left: $spacing;
    }
  }
}


//底部
.bottom-buttons-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  @include flex-center;
  justify-content: space-between;
  background-color: white;
  padding: $spacing $spacing $spacing*2;
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);

  .report-button {
    display: flex;
    align-items: center;

    .report-icon {
      width: $icon-size;
      height: $icon-size;
      margin-right: $spacing / 2;
    }

    .report-text {
      font-size: 14px;
    }
  }

  .buy-button {
    background-color: $buy-button-bg-color;
    color: $buy-button-text-color;
    border: none;
    border-radius: 20px;
    padding: 8px 20px;
    font-size: 14px;
  }
}

.private_message_area {
  width: 100%;
  height: 240rpx;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 388;
  transform: translate3d(0, 100%, 0);
  transition: all 0.3s cubic-bezier(0.25, 0.5, 0.5, 0.9);
  border-top: 1rpx solid #eee;

  .generateClose {
    height: 98rpx;
    font-size: 28rpx;
    color: #333333;
    border-top: 1px solid #eee;
  }
}

.private_message_area .on {
  transform: translate3d(0, 0, 0);
}

.generate-posters {
  width: 100%;
  height: 340rpx;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 388;
  transition: all 0.3s cubic-bezier(0.25, 0.5, 0.5, 0.9);
  background: #fff;
  border-radius: 20px;
  .generateCon {
    height: 220rpx;
  }

  .generateClose {
    height: 98rpx;
    font-size: 28rpx;
    color: #333333;
    border-top: 1px solid #eee;
  }

  .item {
    .pictrue {
      width: 96rpx;
      height: 96rpx;
      border-radius: 50%;
      margin: 0 auto 6rpx auto;

      ::v-deep image,
      .easy-loadimage,
      image,
      uni-image {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }
  }
}

.generate-posters .item {
  flex: 1;
  text-align: center;
  font-size: 30rpx;
}

.generate-posters .item .iconfont {
  font-size: 80rpx;
  color: #5eae72;
}

.generate-posters .item .iconfont.icon-haibao {
  color: #5391f1;
}

.generate-posters .item .iconfont.icon-haowuquan1 {
  color: #ff954d;
}
.contact-popup {
  background: #fff;
  border-radius: 20px;
  padding: 48rpx 24rpx 32rpx 24rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 500rpx;
  box-shadow: 0 8px 32px rgba(169, 122, 76, 0.10);
  animation: fadeIn 0.4s;
  .contact-title {
    font-size: 22px;
    font-weight: bold;
    color: #a97a4c;
    margin-bottom: 12px;
    text-align: center;
    letter-spacing: 1px;
  }
  .contact-desc {
    font-size: 15px;
    color: #888;
    margin-bottom: 28px;
    text-align: center;
  }
  .contact-card {
    width: 100%;
    background: linear-gradient(90deg, #f7f3ed 0%, #fdf6ee 100%);
    border-radius: 14px;
    padding: 22rpx 28rpx;
    margin-bottom: 18px;
    display: flex;
    align-items: center;
    cursor: pointer;
    box-shadow: 0 2px 8px #f3f1ed;
    border: 1px solid #f0e6d8;
    transition: background 0.2s, box-shadow 0.2s;
    &:active {
      background: #f3e9de;
      box-shadow: 0 1px 4px #e6e1d7;
    }
    .contact-label {
      font-size: 16px;
      color: #a97a4c;
      margin-right: 4px;
      font-weight: 500;
      min-width: 60px;
    }
    .contact-value {
      font-size: 18px;
      color: #333;
      font-weight: bold;
      flex: 1;
      word-break: break-all;
      letter-spacing: 1px;
    }
    .contact-copy {
      font-size: 13px;
      color: #bfa074;
      margin-left: 10px;
      background: #f7f3ed;
      border-radius: 8px;
      padding: 2px 10px;
    }
  }
  .contact-card + .contact-card {
    margin-top: 0;
    border-top: 1px solid #f0e6d8;
  }
  .contact-tip {
    color: #bfa074;
    font-size: 14px;
    text-align: center;
    margin-top: 12px;
    letter-spacing: 1px;
  }
}
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(30px);}
  to { opacity: 1; transform: translateY(0);}
}
.share-popup {
  padding: 48rpx 24rpx 32rpx 24rpx;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(169, 122, 76, 0.10);
  display: flex;
  flex-direction: column;
  align-items: center;
  animation: fadeIn 0.4s;
  .share-title {
    font-size: 22px;
    font-weight: bold;
    color: #a97a4c;
    margin-bottom: 12px;
    text-align: center;
    letter-spacing: 1px;
  }
  .share-desc {
    font-size: 15px;
    color: #888;
    margin-bottom: 28px;
    text-align: center;
  }
  .share-actions {
    display: flex;
    justify-content: center;
    gap: 24px;
    margin-bottom: 18px;
    width: 100%;
    .share-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      background: linear-gradient(90deg, #f7f3ed 0%, #fdf6ee 100%);
      border-radius: 14px;
      padding: 24rpx 32rpx;
      border: 1px solid #f0e6d8;
      box-shadow: 0 2px 8px #f3f1ed;
      font-size: 16px;
      color: #a97a4c;
      font-weight: 500;
      transition: background 0.2s, box-shadow 0.2s;
      .share-icon {
        width: 48rpx;
        height: 48rpx;
        margin-bottom: 8px;
      }
      &:active {
        background: #f3e9de;
        box-shadow: 0 1px 4px #e6e1d7;
      }
    }
  }
  .share-tip {
    color: #bfa074;
    font-size: 14px;
    text-align: center;
    margin-top: 12px;
    letter-spacing: 1px;
  }
}
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(30px);}
  to { opacity: 1; transform: translateY(0);}
}
.state-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;
  height: 60rpx;
}
.dot {
  width: 8rpx;
  height: 8rpx;
  background: #bbb;
  border-radius: 50%;
  margin: 0 3rpx;
  animation: dot-blink 1.2s infinite both;
}
.dot:nth-child(2) {
  animation-delay: 0.2s;
}
.dot:nth-child(3) {
  animation-delay: 0.4s;
}
@keyframes dot-blink {
  0%, 80%, 100% { opacity: 0.3; }
  40% { opacity: 1; }
}
.state-anim {
  max-height: 0px;
  opacity: 1;
  overflow: hidden;
  transition: all 8s cubic-bezier(.55,0,.1,1);
}
.state-anim--show {
  max-height: 48px;
  opacity: 0.85;
}
//.speed-float-group {
//  position: fixed;
//  right: 30rpx;
//  bottom: 128rpx;
//  width: 90rpx;
//  height: 90rpx;
//  z-index: 10001;
//}
//.speed-float-ball {
//  width: 90rpx;
//  height: 90rpx;
//  background: #CC8437;
//  color: #fff;
//  border-radius: 50%;
//  box-shadow: 0 4px 16px rgba(139, 69, 19, 0.18);
//  display: flex;
//  align-items: center;
//  justify-content: center;
//  font-size: 30rpx;
//  font-weight: bold;
//  border: 2px solid #AE632C;
//  user-select: none;
//  cursor: pointer;
//  position: absolute;
//  top: 0;
//  left: 0;
//  z-index: 2;
//  transition: box-shadow 0.2s;
//  &:active {
//    box-shadow: 0 2px 8px rgba(139, 69, 19, 0.12);
//  }
//}
//.speed-float-mini {
//  width: 70rpx;
//  height: 70rpx;
//  background: #CC8437;
//  color: #fff;
//  border-radius: 50%;
//  box-shadow: 0 2px 8px rgba(139, 69, 19, 0.12);
//  display: flex;
//  align-items: center;
//  justify-content: center;
//  font-size: 22rpx;
//  font-weight: bold;
//  border: 2px solid #AE632C;
//  user-select: none;
//  cursor: pointer;
//  position: absolute;
//  top: 10rpx; /* (90-70)/2 to center */
//  left: 10rpx;
//  z-index: 1;
//  opacity: 0;
//  transform: translate(0,0);
//  transition: transform 0.35s cubic-bezier(.55,0,.1,1), opacity 0.2s;
//
//  &.show {
//    opacity: 1;
//    &.pos-0 { transform: translate(0rpx, -120rpx); }
//    &.pos-1 { transform: translate(-84.85rpx, -84.85rpx); }
//    &.pos-2 { transform: translate(-120rpx, 0rpx); }
//    &.pos-3 { transform: translate(-84.85rpx, 84.85rpx); }
//    &.pos-4 { transform: translate(0rpx, 120rpx); }
//  }
//}
.speed-float-group2 {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  width: 230rpx;
  z-index: 10001;
  transform: translateX(230rpx);
  transition: transform 0.15s ease-in-out;
  pointer-events: none;
}
.speed-float-group2.visible {
  transform: translateX(0);
  pointer-events: auto;
}
.speed-float-group2.fullscreen .speed-float-ball2 {
  width: 70rpx;
  height: 70rpx;
  font-size: 18rpx;
}
.speed-float-group2.fullscreen .speed-float-mini2 {
  width: 50rpx;
  height: 50rpx;
  font-size: 18rpx;
}
.speed-float-group2.fullscreen .speed-float-mini2.show.pos-0 {
  transform: translate(0rpx, -90rpx);
}
.speed-float-group2.fullscreen .speed-float-mini2.show.pos-1 {
  transform: translate(-64rpx, -64rpx);
}
.speed-float-group2.fullscreen .speed-float-mini2.show.pos-2 {
  transform: translate(-90rpx, 0rpx);
}
.speed-float-group2.fullscreen .speed-float-mini2.show.pos-3 {
  transform: translate(-64rpx, 64rpx);
}
.speed-float-group2.fullscreen .speed-float-mini2.show.pos-4 {
  transform: translate(0rpx, 90rpx);
}
.speed-float-ball2 {
  width: 90rpx;
  height: 90rpx;
  background: #CC8437;
  color: #fff;
  border-radius: 50%;
  box-shadow: 0 4px 16px rgba(139, 69, 19, 0.18);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 22rpx;
  font-weight: bold;
  border: 2px solid #AE632C;
  user-select: none;
  cursor: pointer;
  position: absolute;
  top: 40%;
  right: 30rpx;
  z-index: 2;
  transition: box-shadow 0.2s;
  &:active {
    box-shadow: 0 2px 8px rgba(139, 69, 19, 0.12);
  }
}
.speed-float-mini2 {
  width: 70rpx;
  height: 70rpx;
  background: #CC8437;
  color: #fff;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(139, 69, 19, 0.12);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22rpx;
  font-weight: bold;
  border: 2px solid #AE632C;
  user-select: none;
  cursor: pointer;
  position: absolute;
  top: calc(40% + 10rpx);
  right: 30rpx;
  z-index: 1;
  opacity: 0;
  transform: translate(0,0);
  transition: transform 0.35s cubic-bezier(.55,0,.1,1), opacity 0.2s;

  &.show {
    opacity: 1;
    &.pos-0 { transform: translate(0rpx, -120rpx); }
    &.pos-1 { transform: translate(-84.85rpx, -84.85rpx); }
    &.pos-2 { transform: translate(-120rpx, 0rpx); }
    &.pos-3 { transform: translate(-84.85rpx, 84.85rpx); }
    &.pos-4 { transform: translate(0rpx, 120rpx); }
  }
}
</style>